import React, { useState, useEffect, useCallback, useImperativeHandle, forwardRef } from 'react';
import { Table, Pagination, Button, Dialog, Message } from '@alifd/next';
import IceContainer from '@icedesign/container';
import Filter from '../Filter';
import styles from './index.module.scss';
import http from '../../../../utils/request';
import Moment from 'moment';

export default function GoodsTable({ refs, ...props }) {
  const [current, setCurrent] = useState(1);
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [visible, setVisible] = useState(false);
  const [seeData, setSeeData] = useState({
    type: '',
    title: '',
    list: {

    }
  });

  useImperativeHandle(refs, () => ({
    fetchData: () => {
      fetchData();
    }
  }))

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = useCallback((len, page) => {
    setLoading(true);
    const url = 'all-list';
    const params = {
      limit: 10,
      page: page ? page : 1,
    }
    if (len) {
      params.title = len.title;
      params.type = len.type;
    }
    http.get(url, { params }).then((res) => {
      if (res && res.data.code === 0) {
        setData(res.data.data.list);
        setLoading(false);
        setTotal(res.data.data.total);
      }
    })
  });

  const handlePaginationChange = async (currentPage) => {
    await setCurrent(currentPage);
    fetchData('', currentPage);
  };

  const handleFilterChange = (val) => {
    fetchData(val);
  };

  const handleDelete = (value) => {
    Dialog.confirm({
      title: '提示',
      content: '确认删除吗',
      onOk: () => {
        http.get('delete/' + value._id).then((res) => {
          if (res && res.data.data.ok === 1) {
            fetchData('', 1);
            Message.success('删除成功!');
          } else {
            Message.error('删除失败!');
          }
        })
      },
    });
  };

  const handleDetail = (record) => {
    setSeeData(record);
    setVisible(true);
  };
  // 修改
  const handleEdit = (record) => {
    props.Edit(record);
  }
  const renderOper = (value, index, record) => {
    return (
      <div>
        <Button
          type="primary"
          className={styles.btn}
          onClick={() => handleDetail(record)}
        >
          详情
        </Button>
        <Button
          type="primary"
          className={styles.btn}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Button type="normal" warning onClick={() => handleDelete(record)}>
          删除
        </Button>
      </div>
    );
  };
  const Cell = (value, index, record) => {
    let result = '';
    switch (value) {
      case 'single':
        result = '单选';
        break;
      case 'multi':
        result = '多选';
        break;
      case 'answer':
        result = '解答题';
        break;
    }
    return result;
  }
  const formatterTime = (value, index, record) => {
    if (value) {
      return Moment(value.create_time).format('YYYY-MM-DD');
    } else {
      return '';
    }
  }
  return (
    <div className={styles.container}>
      <IceContainer>
        <Filter onChange={handleFilterChange} />
      </IceContainer>
      <IceContainer>
        <Table loading={isLoading} dataSource={data} hasBorder={false}>
          <Table.Column title="标题" dataIndex="title" />
          <Table.Column title="类型" dataIndex="type" cell={Cell} />
          <Table.Column title="创建时间" dataIndex="create_time" cell={formatterTime} />
          <Table.Column title="更新时间" dataIndex="update_time" cell={formatterTime} />
          <Table.Column
            title="操作"
            width={250}
            dataIndex="oper"
            cell={renderOper}
          />
        </Table>
        <Pagination
          total={total}
          className={styles.pagination}
          current={current}
          onChange={handlePaginationChange}
        />
      </IceContainer>
      {/* 查看详情页面 */}
      <Dialog
        title="查看"
        visible={visible}
        footer={<Button type="primary" onClick={() => setVisible(false)}>取消</Button>}
        onCancel={() => setVisible(false)}
        onClose={() => setVisible(false)}>
        <div style={{ width: '500px', marginBottom: '20px' }}>
          类型: {Cell(seeData.type)}
        </div>
        <div>
          题目:
          {seeData.title}
          {
            seeData.type !== 'answer' ?
              <div>
                <div style={{ marginTop: '20px' }}>
                  答案:
              </div>
                <p>A: {seeData.list.A}</p>
                <p>B: {seeData.list.B}</p>
                <p>C: {seeData.list.C}</p>
                <p>D: {seeData.list.D}</p>
              </div>
              : null
          }
        </div>
      </Dialog>
    </div>
  );
}
